<template>
  <div>
    <!-- 设备树结构--组件 -->
    <deviceTree ref="deviceTree1" @send_selectID="checked_change"></deviceTree>
    <div id="graphContainer2"></div>
    <!-- socket状态组件 -->
    <!-- <socketStatus ref="socketStatus1" :send_data="send_socketArr"></socketStatus> -->
  </div>
</template>
 
<script>
import deviceTree from './statusModal/deviceTree.vue'
import socketStatus from './statusModal/socketStatus'
import "./graph/Init";
import mxgraph from "./graph/index";
import Toolbar from "./graph/Toolbar";
import EditorUi from "./graph/EditorUi2";
import Editor from "./graph/Editor";
import "./graph/Shapes";
import UrlParams from "./graph/UrlParams";
import { Menus } from "./graph/Menus";
import grapheditorTxt from "./resources/grapheditor.txt";
import defaultXml from "./styles/default.xml";
import graphApi from "../../api/graph.api";

const {
  mxGraph,
  mxConstants,
  mxOutline,
  mxEvent,
  mxCell,
  mxGeometry,
  mxUtils,
  mxEventObject,
  mxConnectionHandler,
  mxRubberband,
  mxToolbar,
  mxResources,
  mxCodec
} = mxgraph;

import { Graph } from "./graph/Graph";
import { setTimeout, setInterval } from "timers";
export default {
  components: { deviceTree, socketStatus },
  data() {
    return {
      mGraph: null,
      webstock: null, // new WebSocket(http_ip);
      send_socketArr: [], //父传给子组件的变量
      new_arry: [],
      checkedId: "",
      name: "",
      xml: null,
      showXmlData: [], //xml数据
      new_showXmlData: [],
      flage: false
    }
  },
  methods: {
    //子组件-deviceTree.vue 传过来的selectid
    checked_change(id){
      if(id){
        console.log("id:", id);
        this.checkedId = id;
        graphApi.detail(this.checkedId).then(res => {
          //页面销毁时关闭长连接
          if (this.webstock !== null) {
            this.webstock.close(); //关闭websocket
          }
          let data = res.data.data;
          this.name = data.name;
          this.xml = data.xml;
          this.init();
          console.log("deviceid是否存在：",this.send_socketArr);
          if( this.send_socketArr.length > 0){
            // this.$refs.socketStatus1.socket(); //调子组件的方法
            this.socket(); //封装websocket
          }
        })
      }
    },
    
    init() {
      let self = this;
      let editorUiInit = EditorUi.prototype.init;
      EditorUi.prototype.init = function() {
        editorUiInit.apply(this, arguments);
        // console.log(editorUiInit,this)
        // editorUiInit.toolbar = false;
        // Updates action states which require a backend
        // this.actions.get("open").setEnabled(false);
        // this.actions.get("lockUnlock").setEnabled(false);
      };

      // Adds required resources (disables loading of fallback properties, this can only
      // be used if we know that all keys are defined in the language specific file)
      mxResources.loadDefaultBundle = false;
      mxResources.parse(grapheditorTxt);

      // Configures the default graph theme
      var themes = new Object();
      themes[Graph.prototype.defaultThemeName] = mxUtils.parseXml(
        defaultXml
      ).documentElement;

      // Main
      let mEditorUi = new EditorUi(
        new Editor(UrlParams["chrome"] == "0", themes),
        document.getElementById("graphContainer2")
      );
      let mGraph = mEditorUi.editor.graph;
      self.mGraph = mGraph
      mGraph.setEnabled(false); // 不可编辑设置
      mGraph.getView().updateStyle = true; // 动态改变样式
      mGraph.setResizeContainer(true);// 容器大小自适应
      mGraph.setCellsResizable(false);// 禁止改变元素大小 
      mGraph.edgeLabelsMovable = false; // 禁用移动标签
      mGraph.setVertexLabelsMovable(true); // 允许移动 Vertex 的 Label
      
      if (self.xml) {
        mEditorUi.editor._id = self.id;
        mEditorUi.editor.filename = self.name;
        mGraph.getModel().beginUpdate(); // 开启更新
        try {
          const doc = mxUtils.parseXml(self.xml);
          const root = doc.documentElement;
          const dec = new mxCodec(root.ownerDocument);
          dec.decode(root, mGraph.getModel());
          // console.log( "doc:", doc, dec, dec.decode(root, mGraph.getModel()));
          // var allCells = Object.values(mGraph.getModel().cells); //当前页面所有的cell
          // console.log("当前页面cell:", allCells);
          // console.log("111:",dec, dec.objects, allCells);
          var xmlArry = [];
          // dec.objects数据过滤 empty的cell
          dec.objects.map(k=>{
            if (k){
              xmlArry.push(k);
            }
          })
          // console.log("xmlArry:", xmlArry);
          self.showXmlData = xmlArry;
          xmlArry.map(v=>{
            if ( v.deviceId && v.deviceId !== undefined ) {
              v.deviceId = v.deviceId.toString(); //转成字符串
              // _num传入的数字，m需要的字符长度
              let _num = v.deviceId;
              let m = 17;
              function PrefixInteger(_num, m) {
                return (Array(m).join(0) + _num).slice(-m);
              }
              // console.log((Array(m).join(0) + _num).slice(-m))
              v.deviceId = (Array(m).join(0) + _num).slice(-m);

              self.send_socketArr.push(v.deviceId);
              self.send_socketArr = [...new Set(self.send_socketArr)];
              // console.log(v, self.send_socketArr);
            } else {
              //如果没有deviceId就return
              return false;
            }
          })
        } finally {
          mGraph.getModel().endUpdate(); // 结束更新
        }
      }
    },
    // socket 返回的状态改变
    changeStatus(){
      let mGraph = this.mGraph
      var allCells = Object.values(mGraph.getModel().cells); //当前页面所有的cell
      // console.log("当前页面cell:", allCells);
      // console.log("111:",dec, dec.objects, allCells);
      var xmlArry = [];
      allCells.map(k=>{
        if (k){
          xmlArry.push(k);
        }
      })
      // console.log("xmlArry:", xmlArry);
      this.showXmlData = xmlArry;
      xmlArry.map(v=>{
        if ( v.deviceId && v.deviceId !== undefined ) {
          v.deviceId = v.deviceId.toString(); //转成字符串
          // _num传入的数字，m需要的字符长度
          let _num = v.deviceId;
          let m = 17;
          function PrefixInteger(_num, m) {
            return (Array(m).join(0) + _num).slice(-m);
          }
          // console.log((Array(m).join(0) + _num).slice(-m))
          v.deviceId = (Array(m).join(0) + _num).slice(-m);

          this.send_socketArr.push(v.deviceId);
          this.send_socketArr = [...new Set(this.send_socketArr)];
          // console.log(v, this.send_socketArr);
        } else {
          //如果没有deviceId就return
          return false;
        }
      })
      //有级别value走
      if (this.flage){

        this.new_showXmlData.map((v, i)=>{
          mGraph.getModel().beginUpdate(); // 开启更新
          try {
            //未绑定id的
            var imgNumber = "11";
            //状态级别--最新版: 0 (11)-- 蓝色默认 / 3 (11)--在线  2(10)-- 灰色  1 (02)-- 绿色(一般告警)  4(03)-- 橙色(严重告警)  -1 (04)-- 红色(重要告警)
            var showStatusName = ""; //设备状态文字提示
            if ( v == undefined) return false;
            if ( v.deviceId && v.deviceId !== undefined && v.deviceName && v.statusLevel){
                showStatusName = v.statusValue;
              if ( v.statusLevel == 0){
                imgNumber = "11"; //默认蓝色
              } else if( v.statusLevel == 1){
                imgNumber = "02";
              } else if( v.statusLevel == 2){
                imgNumber = "10";                  
              } else if( v.statusLevel == 3){
                imgNumber = "11";                     
              } else if( v.statusLevel == 4){
                imgNumber = "03";
              } else if( v.statusLevel == -1){
                imgNumber = "04";
              } else {
                showStatusName = v.statusValue;
                imgNumber = "11";
              }
            }

            let newCell = xmlArry[i];
            imgNumber = imgNumber;
            // console.log("imgNumber:", imgNumber);
            newUpdateStyle(newCell, imgNumber, showStatusName);//回调下面的fun
              //更新视图
              //mGraph.refresh()
            /*
              * newCell: 当前的 cell 对象
              */
            function newUpdateStyle(newCell, imgNumber, showStatusName) {
              // newCell里面有style才走
              if(newCell && newCell.style){
                // 判断newCell.style是否同时包含：html=1, image, image=
                let _str = newCell.style;
                // 动态替换图片 
                if( _str.indexOf("html=1") != -1 && _str.indexOf("image") != -1 && _str.indexOf("image=") != -1){
                  let imgStyle1 = "";
                  let resultStyleStr = "";
                  // console.log("newCell.style:", newCell.style);
                  let temp = newCell.style.split(";"); // [image;html=1;image=/static/stencils/clipart/device-01_128x128.png;fillColor=green;strokeColor=blue;]
                  // console.log("temp:", temp);
                  temp.map((v, index) => {
                    if (temp[index].indexOf("image=") != -1 ) {
                      imgStyle1 = temp[index];
                      // console.log("0000:", imgStyle1);
                      let font = imgStyle1;
                      let behind = imgStyle1;
                      let index2 = font.lastIndexOf("/")
                      font = font.substring(0, index2);

                      let index1 = behind.lastIndexOf("/")
                      let behind1 = "";
                      behind = behind.substring(index1+1, behind.length);
                      behind1 = behind;

                      let end1 = "";
                      let end2 = "";
                      end1 = behind.split("-")[0];

                      end2 = behind1.split("-")[1];
                      end2 = end2.substring(0,0) + imgNumber.toString() + end2.substring(2);

                      temp[index] = font + '/' + end1 + '-' + end2;
                      resultStyleStr = 'image;html=1;' + temp[index] + ';';
                    }

                  });
                  // console.log("11111:", temp, resultStyleStr);
                  newCell.style = resultStyleStr;
                }
                //设备状态文字提示
                mGraph.setAttributeForCell(newCell, '在线状态', showStatusName);
                mGraph.setAttributeForCell(newCell, '状态级别', showStatusName);
              }
            }

          } finally {
            mGraph.getModel().endUpdate(); // 结束更新
          }
        })
      }

    },
    //封装websocket
    socket() {
      if (typeof WebSocket != "undefined") {
        this.initWebSocket(); // 开启WebSocket长连接
      } else {
        this.$alert("您的浏览器不支持Websocket通信协议，请使用Chrome或者Firefox浏览器！","温馨提示：");
      }
    },
    /**
     * webstocket 开启长连接
     */
    initWebSocket() {
      //页面刚进入时开启长连接
      // const http_ip ="ws://" +this.$store.state.user.Websocket_AlarmDispatchSrv_ip +":" +
      // this.$store.state.user.Websocket_AlarmDispatchSrv_port;
      const http_ip = "ws://192.168.25.90:7001/";
      this.webstock = new WebSocket(http_ip);
      // console.log("ip:", http_ip);
      this.webstock.onopen = this.webstockonopen;
      this.webstock.onmessage = this.webstockonmessage;
      this.webstock.onclose = this.webstockclose;
      this.webstock.onerror = this.webstockonerror;
    },
    /**
     * webstock连接成功
     */
    webstockonopen(onopen) {
      // console.log("websocket open 连接成功", onopen,this.send_socketArr,this.showXmlData);
      this.webstock.send(JSON.stringify(this.send_socketArr));
    },
    /**
     * webstock接收消息
     */
    webstockonmessage(message) {
      let webstockArr = JSON.parse(message.data);
      // console.log("返回webstockArr:", webstockArr);
      if (webstockArr == "") {
        // this.$alert("websocket未连接，加载Topo图初始状态","温馨提示：");
      } else {
        if ( this.showXmlData.length <= 0 ) return false;
        if ( webstockArr.length <= 0 ){
          return false;
        } else {
          webstockArr.map(k=>{
            let index = this.new_arry.findIndex(v => v.id === k.deviceId)
            if( index > -1) {
              this.new_arry[index].name = k.deviceName
              this.new_arry[index].level = k.alarmLevel
              this.new_arry[index].status = k.alarmValue
            } else {
              this.new_arry.push({ id:k.deviceId, name:k.deviceName, level:k.alarmLevel, status:k.alarmValue })
            }
          })
          // console.log('组装完成的所有设备信息', this.new_arry);
          this.showXmlData.map(v=>{
            this.new_arry.map(k=>{
              if (v.deviceName && v.deviceId && v.deviceId == k.id ) {
                //如果设备ID相等
                v.statusLevel = k.level
                v.statusValue = k.status
              } else {
                //如果设备ID不相等，或者deviceId不存在
              }
            })
          })
        }
      }
      // console.log("this.showXmlData:", this.showXmlData);
      this.new_showXmlData = this.showXmlData;
      // this.$Message.success('加载设备拓扑图成功！');
    },
    /**
     * webstock关闭
     */
    webstockclose(event) {
      console.log("websocket close"); //监听关闭
    },
    /**
     * webstock出错
     */
    webstockonerror(error) {
      // console.log("websocket error");
      this.webstock.close(); //关闭websocket
      this.initWebSocket(); // 开启WebSocket长连接
    }
  },
  watch: {
    //实时监听socket返回数据的new_showXmlData的变化
    new_showXmlData:function(val){
      console.log("watchData:", val);
      for (let i = 0; i < this.new_showXmlData.length; i++) {
        if(this.new_showXmlData[i].deviceId && this.new_showXmlData[i].deviceId !== undefined && this.new_showXmlData[i].deviceName && this.new_showXmlData[i].statusLevel ){
          this.flage = true;
          // this.init();
        }
      }
      //如果有socket返回状态
      if(this.flage){
        this.changeStatus();
      }
    }
  },
  created() {},
  mounted() {
    // window.onload = function(){
    //   var el = document.getElementById("graphContainer2");
    //   el.oncontextmenu = function(e) {
    //     console.log("eee:", e)
    //     //左键--button属性=1，右键button属性=2
    //     if (e){
    //       e.cancelBubble = true 
    //       e.returnvalue = false;
    //       return false; //屏蔽右键菜单
    //     }
    //   }
    // }
  },
  destroyed() {
    // 销毁 panZoomTiger 实例
    this.$destroy();
    //页面销毁时关闭长连接
    if (this.webstock !== null) {
      this.webstock.close(); //关闭websocket
    }
    this.showXmlData = [];
    this.new_showXmlData = [];  
  }
};
</script>

<style scoped>
@import "./styles/grapheditor.css";
</style>
<style scoped>
>>>#graphContainer2{
  width: 100%;
  height: 100%;
  min-height: 780px !important;
  position: relative;
  top: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
>>>#graphContainer2 .geDiagramContainer.geDiagramBackdrop{
  top: 0px !important;
  width: 100% !important;
  height: 100% !important;
  overflow: hidden !important;
}
>>>#graphContainer2 .geBackgroundPage {
  top: 0px !important;
  left: 0px !important;
  /* width: 3950px !important; */
  width: 100% !important;
  height: 100% !important;
  /* min-height: 700px !important; */
}
>>>#graphContainer2 .geDiagramContainer.geDiagramBackdrop svg{
  /* left: 0px !important; */
  cursor: pointer; /*画布加鼠标小手样式*/
  background: url('/static/images/bgimg.png') no-repeat !important;
  /* background-color: rgb(41, 0, 83); */
}
</style>